<template>
  <el-popover placement="top" width="250" v-model="visible" trigger="click">
    <div class="container">
      <a href="http://cn.gravatar.com/" target="_blank">
<!--        <el-avatar :size="64" fit="fill" :src="account.avatar"></el-avatar>-->
      </a>
      <span style="display: block">{{ account.name }}</span>
      <el-form ref="account_form" :model="account" :rules="rules" size="small" class="account_form">
        <el-form-item size="small" prop="email">
          <el-input v-model="account.email">
            <template v-slot:prepend
              ><el-icon><Promotion /></el-icon
            ></template>
          </el-input>
        </el-form-item>
        <el-form-item size="small" prop="telephone">
          <el-input v-model="account.telephone">
            <template v-slot:prepend
              ><el-icon><Iphone /></el-icon
            ></template>
          </el-input>
        </el-form-item>
        <el-form-item size="small" prop="location">
          <el-input v-model="account.location">
            <template v-slot:prepend
              ><el-icon><MapLocation /></el-icon
            ></template>
          </el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: center; margin: 5px 0 5px 0">
        <el-button size="small" type="primary" plain @click="modifyAccount">更新信息</el-button>
        <el-button size="small" type="danger" plain @click="exitLogin">退出登录</el-button>
      </div>
    </div>
    <template v-slot:reference>
      <el-button
        :icon="userStore.isAuthorized ? 'UserFilled' : 'User'"
        circle
        @click="changeUserStatue"
      ></el-button>
    </template>
  </el-popover>
</template>

<script setup>
import api from '@/api'
import { onMounted, reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'
import { Iphone, MapLocation, Promotion } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
// const { account, session } = storeToRefs(userStore)

const account = ref(userStore.EMPTY_ACCOUNT())

const trigger = ref('manual')
let visible = ref(false)

const account_form = ref()

const rules = reactive({
  email: [
    { required: true, message: '请填写邮箱', trigger: 'blur' },
    { type: 'email', message: '不符合邮箱格式', trigger: 'blur' },
  ],
  telephone: [{ required: true, message: '请填写手机', trigger: 'blur' }],
  location: [{ required: true, message: '请填写地址', trigger: 'blur' }],
})

onMounted(() => {
  if (userStore.isAuthorized) {
    // Session是具有有效期的，设置更新令牌的触发器
    userStore.refreshSessionTrigger()
    // Session中有用户，而账号中没有，说明是通过“保存当前登陆状态”得到的，从服务端获取一下用户信息
    if (!userStore.state.account.username) {
      refreshAccount()
      account.value = userStore.state.account
    }
  }
})

/**
 * 检查用户状态
 * 没有登陆的话，转向登陆页面
 */
function changeUserStatue() {
  if (!userStore.isAuthorized) {
    router.push('/login')
  }
}
/**
 * 从服务端请求用户信息，更新到vuex中
 */
async function refreshAccount() {
  let { data } = await api.account.getAccountByUsername(userStore.state.session.username)
  // 上传头像的功能不做了，直接用Gravatar的服务
  data.avatar = api.encrypt.gravatarEncode(data.email)
  userStore.updateAccount(data)
}

/**
 * 退出登陆
 */
function exitLogin() {
  userStore.clearSession()
  visible.value = false
}

/**
 * 更新账户信息
 */
function modifyAccount() {
  account_form.value.validate((valid) => (valid ? submitModification() : false))
}
/**
 * 向服务端提交账户更新
 */
async function submitModification() {
  try {
    await api.account.updateAccount(account)
    ElNotification({ title: '成功', message: '账号信息已成功更新', type: 'success' })
  } catch (e) {
    ElNotification({ title: '失败', message: e.message, type: 'error' })
  }
}
</script>

<style scoped>
.container {
  display: block;
  text-align: center;
}

.account_form {
  padding-top: 15px;
}
</style>
